package com.jasiri.project.ui.user.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Build
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import com.google.android.gms.auth.api.phone.SmsRetriever
import com.google.android.gms.common.api.CommonStatusCodes
import com.google.android.gms.common.api.Status
import com.jasiri.project.R
import com.jasiri.project.app.App
import com.jasiri.project.databinding.ActivityMobileCheckBinding
import com.jasiri.project.databinding.ActivityMobileCheckTypeBinding
import com.jasiri.project.lib.dev.JasiriSysDataHelper
import com.jasiri.project.pro.ProActivity
import com.jasiri.project.utils.BarUtils
import com.jasiri.project.utils.config.Configs
import com.jasiri.project.utils.dialog.BirthdayDialog
import com.jasiri.project.utils.dialog.SubmitSuccessDialog
import com.jasiri.project.utils.event.EventType
import com.jasiri.project.utils.event.track.TrackEventManager
import com.jasiri.project.utils.helper.ActivityStackHelper
import com.jasiri.project.utils.helper.JasiriMainProcessHelper
import com.jasiri.project.utils.http.AppUrls
import com.jasiri.project.utils.http.AppUrls.addCommonParams
import com.jasiri.project.utils.http.IHttpCallback
import com.jasiri.project.utils.log.HHLog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2025/2/18 11:37
 * @Annotation：手机号校验
 */
class MobileCheckActivity: ProActivity(), CoroutineScope by MainScope() {
    lateinit var binding:ActivityMobileCheckBinding
    //检验类型列表
    private var checkTypeList = arrayListOf<JSONObject>()
    private var selectCheckType = ""

    private var smsBroadcastReceiver: CheckMobileBroadcastReceiver? = null
    private val SMS_CONSENT_REQUEST = 200
    //等待时长
    private var countdownTimer: MyCountDownTimer? = null
    private var countdown = 60

    //是否需要选择出生日期
    private var needSubmitBirthDay = "NO"
    //出生日期选择
    private var birthdayDialog: BirthdayDialog? = null

    companion object {
        fun start(context: Context) {
            //当前栈顶是 手机号校验页面 不重复跳转
            if (ActivityStackHelper.isCurrentActivity(MobileCheckActivity::class.java)){
                return
            }
            val intent = Intent(context, MobileCheckActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun getRootView(): View {
        binding = ActivityMobileCheckBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        setBackExit(true)
        binding.mobileCheckParentLayout.setPadding(0, BarUtils.getStatusBarHeight(),0,0)
        initMobileCheckRefreshLayout()
        showChcekMobileTypeView(false)

        EventBus.getDefault().register(this)
        SmsRetriever.getClient(this).startSmsUserConsent(null)
        registerSMSBroadcastReceiver()
    }

    override fun initListener() {
        binding.editCode.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                if (getEditMobile().isNotEmpty() && getEditCode().isNotEmpty() && selectCheckType.isNotEmpty()){
                    binding.btnContinue.isEnabled = true
                    binding.btnContinue.alpha = 1f
                } else {
                    binding.btnContinue.isEnabled = false
                    binding.btnContinue.alpha = 0.2f
                }
            }
        })
        binding.editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                binding.btnConfirm.isEnabled = getEditMobile().isNotEmpty()
            }
        })

        //发送验证码
        binding.btnSend.setOnClickListener {
            if (selectCheckType.isEmpty()){
                return@setOnClickListener
            }
            sendCheckMobileWhatsAppCodeAction()
        }

        binding.imgEdit.setOnClickListener {
            showChcekMobileTypeView(true)
        }
        binding.btnConfirm.setOnClickListener {
            if (getEditMobile().isEmpty()){
                return@setOnClickListener
            }
            showChcekMobileTypeView(false)
        }
        //提交
        binding.btnContinue.setOnClickListener {
            if (getEditMobile().isEmpty() || getEditCode().isEmpty()){
                binding.btnContinue.isEnabled = false
                return@setOnClickListener
            }
            onCheckMobileCodeAction()
            TrackEventManager.trackEventNow(EventType.CLICK.CLICK_VERIFICATION_CONTINUE,"${getEditCode()}##${getEditMobile()}")
            //上报位置和陀螺仪数据
            JasiriSysDataHelper.onCheckSubmitDataByTypes(App.instance(), arrayListOf("T11","T12"),"Check Mobile Page")
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        val zoneCode = Configs.getSPString(Configs.SPKEY.JASIRI_TIMEZONE_CODE)
        val mobile = Configs.getSPString(Configs.SPKEY.JASIRI_MOBILE)
        binding.txtZoneCode.text = "+$zoneCode"
        binding.editMobile.setText(mobile)

        binding.btnSend.text = getString(R.string.mobile_check_send)
        binding.btnSend.isEnabled = false
        binding.btnSend.setTextColor(Color.parseColor("#FFFFFFFF"))
        binding.btnSend.setBackgroundResource(R.drawable.circle_fill_ffcfcfcf)

        checkTypeList.clear()
        if (JasiriMainProcessHelper.isJasiriMainAuthCheckSMS()){
            val smsItem = JSONObject()
            smsItem.put("type","SMS")
            smsItem.put("title",getString(R.string.mobile_check_type_sms))
            smsItem.put("iconNormal",R.mipmap.img_mobile_check_sms_normal)
            smsItem.put("iconSelected",R.mipmap.img_mobile_check_sms_selected)
            smsItem.put("isSelected",true)
            selectCheckType = "SMS"
            checkTypeList.add(smsItem)
        }

        if (JasiriMainProcessHelper.isJasiriMainAuthCheckWhatsApp()){
            val whatsAppItem = JSONObject()
            whatsAppItem.put("type","WHATSAPP")
            whatsAppItem.put("title",getString(R.string.mobile_check_type_whatsapp))
            whatsAppItem.put("iconNormal",R.mipmap.img_mobile_check_whatsapp_normal)
            whatsAppItem.put("iconSelected",R.mipmap.img_mobile_check_whatsapp_selected)
            if (selectCheckType.isNotEmpty()){
                whatsAppItem.put("isSelected",false)
            } else {
                whatsAppItem.put("isSelected",true)
                selectCheckType = "WHATSAPP"
            }
            checkTypeList.add(whatsAppItem)
        }
        addCheckTypeViews()
    }

    /* 初始化刷新 */
    private fun initMobileCheckRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            EventBus.getDefault().post(Configs.Event.PROCESS_REFRESH)
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 注册SMS广播接收
     */
    private fun registerSMSBroadcastReceiver(){
        // 2 register receiver
        val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
        smsBroadcastReceiver = CheckMobileBroadcastReceiver {
            startActivityForResult(it, SMS_CONSENT_REQUEST)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上版本使用 receiverFlags 参数
            registerReceiver(smsBroadcastReceiver, intentFilter, SmsRetriever.SEND_PERMISSION, null, Context.RECEIVER_EXPORTED) // 指定导出标志
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android 8.0 到 Android 12 版本使用带权限的 registerReceiver()
            registerReceiver(smsBroadcastReceiver, intentFilter, SmsRetriever.SEND_PERMISSION, null)
        } else {
            // Android 8.0 以下版本，只使用 receiver 和 intentFilter 参数
            registerReceiver(smsBroadcastReceiver, intentFilter)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SMS_CONSENT_REQUEST) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                // 读取短信内容
                val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
                HHLog.e("Sms content: $message")

                // 提取otp
                val code = extractFirstNumber(message)
                HHLog.e("Sms code: $code")
                if (code != null){
                    binding.editCode.setText(code)
                }
            } else {
                // 用户不同意或没收到待
                HHLog.e("User canceled or no message received")
            }
        }
    }

    /**
     * 提取连续的数字
     */
    private fun extractFirstNumber(input: String?): String? {
        if(input.isNullOrBlank()) return ""

        val regex = "\\d+".toRegex()
        return regex.find(input)?.value
    }

    fun getEditMobile(): String {
        return binding.editMobile.text.toString()
    }

    fun getEditCode(): String {
        return binding.editCode.text.toString()
    }


    /**
     * 发送成功提示
     */
    private fun showSendCodeSuccessDialog(){
        val sendSuccessDialog = SubmitSuccessDialog(this)
        sendSuccessDialog.setCancelable(false)
        sendSuccessDialog.setCanceledOnTouchOutside(false)
        sendSuccessDialog.show()
        sendSuccessDialog.showSubmitSuccess(getString(R.string.mobile_check_send_tips))
        Handler(Looper.getMainLooper()).postDelayed({
            sendSuccessDialog.dismiss()
        },1500)
    }

    /**
     * 切换是否修改手机号View
     */
    private fun showChcekMobileTypeView(isEdit: Boolean){
        //是否允许修改手机号码
        if (!JasiriMainProcessHelper.isJasiriMainAuthMobileEditFlag()){
            binding.editMobile.isEnabled = false
            binding.imgEdit.visibility = View.INVISIBLE
            binding.btnConfirm.visibility = View.GONE
            return
        }
        when(isEdit){
            true -> {
                binding.editMobile.isEnabled = true
                binding.editMobile.requestFocus()
                onShowSoftInput(binding.editMobile)
                binding.editMobile.setSelection(getEditMobile().length)
                binding.imgEdit.visibility = View.INVISIBLE
                binding.btnConfirm.visibility = View.VISIBLE
            }
            else -> {
                binding.editMobile.isEnabled = false
                binding.imgEdit.visibility = View.VISIBLE
                binding.btnConfirm.visibility = View.GONE
            }
        }
    }

    /**
     * 设置校验类型列表
     */
    private fun addCheckTypeViews(isEnabled: Boolean = true){
        binding.checkTypeLayout.removeAllViews()
        for (i in 0..<checkTypeList.size){
            val item = checkTypeList[i]
            val typeBinding = ActivityMobileCheckTypeBinding.inflate(layoutInflater)
            typeBinding.checkTypeLayout.isEnabled = isEnabled
            typeBinding.textType.text = item.optString("title")
            when(item.optBoolean("isSelected")){
                true -> {
                    selectCheckType = item.optString("type")
                    typeBinding.checkTypeLayout.setBackgroundResource(R.drawable.mobile_check_type_selected)
                    typeBinding.imgType.setImageResource(item.optInt("iconSelected"))
                    typeBinding.textType.setTextColor(Color.parseColor("#ff3a78fd"))
                    typeBinding.imgTypeCheck.setImageResource(R.mipmap.img_mobile_check_selected)
                }
                else -> {
                    typeBinding.checkTypeLayout.setBackgroundResource(R.drawable.mobile_check_type_normal)
                    typeBinding.imgType.setImageResource(item.optInt("iconNormal"))
                    typeBinding.textType.setTextColor(Color.parseColor("#FFCFCFCF"))
                    typeBinding.imgTypeCheck.setImageResource(R.mipmap.img_mobile_check_normal)
                }
            }
            typeBinding.checkTypeLayout.setOnClickListener {
                if (item.optBoolean("isSelected")){
                    return@setOnClickListener
                }
                checkTypeList.forEach {
                    if (it.optString("title") == item.optString("title")){
                        it.put("isSelected",true)
                        if (it.optString("title") == getString(R.string.mobile_check_type_sms)){
                            addEvent(EventType.CLICK.CLICK_VERIFICATION_SMS,"")
                        } else {
                            addEvent(EventType.CLICK.CLICK_VERIFICATION_WHATSAPP,"")
                        }
                    } else {
                        it.put("isSelected",false)
                    }
                }
                addCheckTypeViews()
                //发送验证码
                sendCheckMobileWhatsAppCodeAction()
            }
            binding.checkTypeLayout.addView(typeBinding.root)
            if (getEditMobile().isNotEmpty() && getEditCode().isNotEmpty() && selectCheckType.isNotEmpty()){
                binding.btnContinue.isEnabled = true
                binding.btnContinue.alpha = 1f
            } else {
                binding.btnContinue.isEnabled = false
                binding.btnContinue.alpha = 0.2f
            }
            binding.btnSend.text = getString(R.string.mobile_check_send)
            if (getEditMobile().isNotEmpty() && selectCheckType.isNotEmpty()){
                binding.btnSend.isEnabled = true
                binding.btnSend.setTextColor(Color.parseColor("#FFFFFFFF"))
                binding.btnSend.setBackgroundResource(R.drawable.btn_selector_circle)
            } else {
                binding.btnSend.isEnabled = false
                binding.btnSend.setTextColor(Color.parseColor("#FFFFFFFF"))
                binding.btnSend.setBackgroundResource(R.drawable.circle_fill_ffcfcfcf)
            }
        }
    }

    fun showMobileCheckSendCodeSuccess(directLoginFlag: String) {
        hideLoading()
        when(directLoginFlag){
            "YES" -> {
                showMobileCheckSuccess()
            }
            else -> {
                startCountdownTimer()
            }
        }
    }

    fun showMobileCheckSuccess() {
        Configs.saveSPString(Configs.SPKEY.JASIRI_MOBILE,getEditMobile())
        EventBus.getDefault().post(Configs.Event.PROCESS_REFRESH)
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        finish()
    }

    /**
     * 选择出生日期
     */
    private fun showBirthDialog(){
        if (birthdayDialog == null){
            birthdayDialog = BirthdayDialog(this,"",object : BirthdayDialog.IDialogCallback{
                override fun completed(selectDate: JSONObject) {
                    //可根据需要自行截取数据显示
                    onCheckMobileCodeAction(selectDate.optString("subDate"))
                }
            })
            birthdayDialog?.setCancelable(true)
            birthdayDialog?.setCanceledOnTouchOutside(false)
        }
        birthdayDialog?.show()
    }

    /**
     * 自动获取短信验证码广播
     */
    class CheckMobileBroadcastReceiver(val result: (Intent) -> Unit): BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            if (SmsRetriever.SMS_RETRIEVED_ACTION == intent.action) {
                val extras = intent.extras
                val status: Status? = extras?.get(SmsRetriever.EXTRA_STATUS) as? Status
                val code = status?.statusCode ?: -1
                if (code == CommonStatusCodes.SUCCESS) {
                    //获取内容Intent，只能通过 startActivityForResult(intent) 才能读取短信内容
                    val consentIntent = extras?.getParcelable<Intent>(SmsRetriever.EXTRA_CONSENT_INTENT)
                    consentIntent?.let {
                        result.invoke(it)
                    }
                }
            }
        }
    }

    class MyCountDownTimer(private val act: MobileCheckActivity, millisInFuture: Int, countDownInterval: Long): CountDownTimer(millisInFuture.toLong(), countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showCheckCountdownText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showCheckCountdownComplete()
        }
    }

    /**
     * 倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun showCheckCountdownText(){
        binding.btnSend.text = "$countdown S"
    }

    /**
     * 倒计时完成
     */
    private fun showCheckCountdownComplete(){
        countdown = 60
        binding.btnSend.text = getString(R.string.mobile_check_send)
        binding.btnSend.isEnabled = true
        binding.btnSend.setTextColor(Color.parseColor("#FFFFFFFF"))
        binding.btnSend.setBackgroundResource(R.drawable.btn_selector_circle)
        addCheckTypeViews(true)
        showChcekMobileTypeView(false)
    }

    /**
     * 启动倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun startCountdownTimer() {
        showSendCodeSuccessDialog()
        addCheckTypeViews(false)
        //随机 60秒 等待时长
        countdown = 60
        binding.btnSend.text = "$countdown S"
        binding.btnSend.isEnabled = false
        binding.btnSend.setTextColor(Color.parseColor("#FFFFFFFF"))
        binding.btnSend.setBackgroundResource(R.drawable.circle_fill_ffcfcfcf)
        //手机号码输入框变成不可编辑状态
        binding.editMobile.isEnabled = false
        binding.imgEdit.visibility = View.INVISIBLE
        binding.btnConfirm.visibility = View.GONE

        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown * 1000, 1000)
        }
        countdownTimer?.start()
    }

    /**
     * 发送WhatsApp验证码
     */
    private fun sendCheckMobileWhatsAppCodeAction(){
        //发送验证，埋点增加手机号
        addEvent(EventType.CLICK.CLICK_VERIFICATION_GETCODE,getEditMobile())
        showLoading()
        val loginMobile = Configs.getSPString(Configs.SPKEY.JASIRI_MOBILE)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.WHATSAPP_SEND_CODE_PATH)
            put("mobile", loginMobile)
            put("submitMobile", getEditMobile())
            put("sendType",selectCheckType)
        }
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        postAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    //是否需要验证生日
                    if (obj.has("needSubmitBirthDay")){
                        needSubmitBirthDay = obj.optString("needSubmitBirthDay")
                    }
                    //当为YES时可以跳过，直接调用流程接口，根据流程步骤whatsappFlag标识走
                    val directLoginFlag = obj.optString("directLoginFlag")
                    showMobileCheckSendCodeSuccess(directLoginFlag)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideLoading()
            }
        })
    }

    /**
     * 校验验证码
     */
    private fun onCheckMobileCodeAction(submitBirthDay: String = ""){
        //需要提交出生日期
        if (needSubmitBirthDay == "YES" && submitBirthDay.isEmpty()){
            showBirthDialog()
            return
        }
        showLoading()
        val loginMobile = Configs.getSPString(Configs.SPKEY.JASIRI_MOBILE)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.WHATSAPP_CHECK_CODE_PATH)
            put("mobile", loginMobile)
            put("submitMobile", getEditMobile())
            put("code",getEditCode())
            put("checkType",selectCheckType)
            put("needSubmitBirthDay",needSubmitBirthDay)//是否需要验证生日
        }
        if (needSubmitBirthDay == "YES" && submitBirthDay.isNotEmpty()){
            params.put("submitBirthDay",submitBirthDay)//出生日期
        }
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        postAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideLoading()
                showMobileCheckSuccess()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideLoading()
            }
        })
    }

    /**
     * 更新总流程完成
     */
    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun onRefreshProcessCompleted(event: String){
        HHLog.e("mobile check>>>>>>>>>>$event")
        when(event){
            Configs.Event.PROCESS_REFRESHED -> {//总流程刷新完成
                hideLoading()
                if (!JasiriMainProcessHelper.isJasiriMainAuthCheckMobile()){
                    //校验成功
                    showMobileCheckSuccess()
                }
            }
        }
    }

    override fun hideLoading() {
        super.hideLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_VERIFICATION_MOBILE_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_VERIFICATION_MOBILE_END,"")
        EventBus.getDefault().unregister(this)
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
        if (smsBroadcastReceiver != null){
            unregisterReceiver(smsBroadcastReceiver)
        }
    }
}